var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

const orderModel = require('../../database/order.js');

router.get('/orders', async (req, res) => {
  try {
    const { search, status, date } = req.query;
    const query = {};
    
    // 搜索关键词：匹配客户名或订单号
    if (search) {
      query.$or = [
        { customer: { $regex: search, $options: 'i' } },
        { id: { $regex: search, $options: 'i' } }
      ];
    }
    
    // 状态筛选
    if (status) {
      query.status = status;
    }
    
    // 日期筛选
    if (date) {
      query.date = date;
    }
    
    const orders = await orderModel.find(query);
    const formattedOrders = orders.map(order => ({
      id: order.id,
      customer: order.customer,
      amount: order.amount,
      status: order.status,
      date: order.date
    }));
    res.json(formattedOrders);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;